package com.xiaoli.mss.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Http访问工具类
 */
public class HttpRequestUtils {

    public static Map<String,String> doGet(String url){
        Map<String,String> map = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpget.
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                ObjectMapper mapper = new ObjectMapper();
                map = mapper.readValue(result, Map.class);
            }
        }catch (Exception ex){

        }finally {
            try {
                response.close();
                httpClient.close();
            } catch (IOException ignore) {}
        }
        // 获取响应实体
        return map;
    }
}
